package com.cn.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.cn.domain.Cart;
import com.cn.domain.Product;
import com.cn.domain.User;
import com.cn.service.CartService;
import com.cn.service.impl.CartServiceImpl;
import com.cn.utils.JsonMapper;


@WebServlet(value="/CartOperServlet")
public class CartOperServlet extends HttpServlet {
	
	//对购物车的CRUD
	private CartService cartService=new CartServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String type=req.getParameter("type");
		String num=req.getParameter("num");//获取需要更新的数量
		
		User user=(User) req.getSession().getAttribute("user");
		String id=req.getParameter("pid");
		System.out.println("num="+num+":cccid="+id+"type="+type);
		//更新页面的数量
		if("update".equals(type)) {
			String reg="\\d+";
			if(num.matches(reg)) {
				cartService.updateCartById(Long.parseLong(num),Long.parseLong(id),user.getHu_user_id());
			}
		}else if("delete".equals(type)) {
			//System.out.println("delete商品的信息！！！");
			if(id!=null) {
				long pid=Long.parseLong(id);
				if(cartService.delCartByPidAndUserId(pid,user.getHu_user_id())>0) {
					System.out.println("删除成功!");
				}
			}
		}else if("goToCart".equals(type)){
			//进入购物车
			if(user==null){
				//用户还没有登录直接跳转到登录页面
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
				return;
			}
		}
		//然后继续查询，刷新页面！
		List<Cart> cartList=null;
		try {
			//按照USERID和PID查询所有的cart物品
			cartList=cartService.queryAllCart(user.getHu_user_id());
			//System.out.println("cartList="+cartList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		req.getSession().setAttribute("shoppingList", cartList);
		req.getRequestDispatcher("/GoToOrderJspServlet").forward(req, resp);
	}
		
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
}
